<script setup lang="ts" name="EaTask">
import { Plus, Edit, Search, ArrowDown } from '@element-plus/icons-vue'
import type { EaTask } from './type'
import Detail from './Detail.vue'
import Form from './Form.vue'

import { checkPermission } from '@/utils/permission'

const baseApi = '/ea/ea-task'

const { queryParam, loading, dataList, pagination, getList, onSearch, resetFilter, remove, batchRemove } =
  useList<EaTask>({ baseApi, initQueryParam: {} })

defineExpose({
  refresh: onSearch,
  addCondition: (key: keyof EaTask, value: any, refresh = false) => {
    queryParam[key] = value
    if (refresh) onSearch()
  }
})

const { initRelatedData, relatedData } = useOption({
  load: {
    memberIdOptions: { type: 'IamMember', label: 'nickname' }
  }
})
initRelatedData()

const sortChange = ({ column, prop, order }: { column: { sortBy?: string }; prop: string; order: string }) => {
  let orderBy: 'ASC' | 'DESC' | undefined
  switch (order) {
    case 'ascending':
      orderBy = 'ASC'
      break
    case 'descending':
      orderBy = 'DESC'
      break
    default:
      orderBy = undefined
  }
  pagination.orderBy = orderBy ? `${column.sortBy ?? prop}:${orderBy}` : undefined
  onSearch()
}

const formRef = ref()
const formTitle = ref('')
const submitting = ref(false)
const formVisible = ref(false)
const addSustainably = ref<boolean>(false)

const openForm = (id?: string) => {
  if (id) {
    addSustainably.value = false
    formTitle.value = '编辑'
  } else {
    addSustainably.value = true
    formTitle.value = '新建'
  }
  formVisible.value = true

  nextTick(() => formRef.value?.init(id))
}

const orderReceivingInfo = id => {
  router.push({
    path: '/ea/ea-task/order-receiving-info',
    query: {
      taskId: id
    }
  })
}

const closeForm = () => {
  formVisible.value = false
}

const submit = (goOn = false) => {
  formRef.value?.submit().then((result: boolean) => {
    if (result) {
      if (!goOn) {
        formVisible.value = false
      }
      formRef.value?.reset()
    }
  })
}

const detailRef = ref()
const detailVisible = ref(false)
const dataId = ref('')

const openDetail = (id: string) => {
  dataId.value = id
  detailVisible.value = true

  nextTick(() => detailRef.value?.init(id))
}

const closeDetail = () => {
  detailVisible.value = false
}
const closeDetailAndOpenForm = () => {
  detailVisible.value = false
  openForm(dataId.value)
}

const handleOperation = (code: string, value?: string | string[]) => {
  switch (code) {
    case 'detail':
      openDetail(value as string)
      break
    case 'create':
    case 'update':
      openForm(value as string)
      break
    case 'remove':
      remove(value as string)
      break
    case 'batchRemove':
      batchRemove(value as string[])
      break
    case 'orderReceivingInfo':
      orderReceivingInfo(value as string)
      break
    default:
      throw new Error(`不存在的操作编码${code}!`)
  }
}

const sum = (prop: keyof EaTask, fractionDigits?: number) =>
  Number(
    (dataList ?? [])
      .map(e => Number(e[prop] ?? 0))
      .reduce((e1, e2) => e1 + e2, 0)
      .toFixed(fractionDigits)
  )

const ave = (prop: keyof EaTask, fractionDigits?: number) =>
  Number(
    ((dataList ?? []).map(e => Number(e[prop] ?? 0)).reduce((e1, e2) => e1 + e2, 0) / (dataList ?? []).length).toFixed(
      fractionDigits
    )
  )

const refreshData = (haveNewData?: boolean) => {
  haveNewData ? onSearch() : getList()
}

const router = useRouter()

const activated = () => {
  nextTick(() => {
    const query = router.currentRoute.value.query
    for (const queryKey in query) {
      queryParam[queryKey as keyof EaTask] = query[queryKey] as any
    }

    onSearch()
  })
}

router.currentRoute.value.meta.keepAlive ? onActivated(activated) : activated()
</script>

<template>
  <div class="list-page">
    <el-space wrap class="list-operation">
      <el-button v-has-permission="'create'" type="primary" :icon="Plus" @click="handleOperation('create')">
        新建
      </el-button>

      <el-space>
        <span class="search">
          <el-select v-model="queryParam.memberId" placeholder="客户" filterable clearable @change="onSearch">
            <el-option v-for="item in relatedData.memberIdOptions" :key="item.value" v-bind="item">
              <div v-if="typeof item.ext === 'string'" class="option">
                {{ item.label }}
                <span class="ext">（{{ item.ext }}）</span>
              </div>
            </el-option>
          </el-select>
        </span>
        <el-button :icon="Search" type="primary" @click="onSearch">查询</el-button>
        <el-button title="重置查询条件" @click="resetFilter">重置</el-button>
      </el-space>
    </el-space>

    <el-table
      ref="tableRef"
      v-loading="loading"
      class="list-body"
      :data="dataList"
      height="100%"
      stripe
      row-key="id"
      style="border-top: 1px solid var(--el-border-color-lighter)"
      @row-dblclick="(row: EaTask) => checkPermission('detail') && handleOperation('detail', row.id)"
      @sort-change="sortChange"
    >
      <el-table-column label="客户" prop="memberIdLabel" show-overflow-tooltip />
      <el-table-column label="工作人数" prop="peopleNum" show-overflow-tooltip>
        <template #header>
          <el-tooltip placement="bottom">
            <template #content>
              当前页总和：{{ sum('peopleNum', 2) }}<br />
              当前页平均：{{ ave('peopleNum', 3) }}
            </template>
            工作人数
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="workAddress" show-overflow-tooltip width="200" />
      <el-table-column label="支付金额" prop="payMoney" show-overflow-tooltip>
        <template #header>
          <el-tooltip placement="bottom">
            <template #content>
              当前页总和：{{ sum('payMoney', 2) }}<br />
              当前页平均：{{ ave('payMoney', 3) }}
            </template>
            支付金额
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="工作要求" prop="workDemand" show-overflow-tooltip />
      <el-table-column label="工种" prop="workTypeIdLabel" show-overflow-tooltip />
      <el-table-column label="任务状态" prop="taskStatusLabel" show-overflow-tooltip>
        <template #default="{ row }: { row: EaTask }">
          <el-tag
            v-if="row.taskStatusLabel"
            effect="dark"
            type="info"
            :color="(row.taskStatusLabel as LabelValue<{ color?: string }>).ext?.color"
          >
            {{ (row.taskStatusLabel as LabelValue).label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" prop="completeTime" show-overflow-tooltip />
      <el-table-column label="详细地址" prop="detailAddress" show-overflow-tooltip />
      <el-table-column label="预约时间" prop="appointmentTime" show-overflow-tooltip />
      <el-table-column label="工种名称" prop="workTypeName" show-overflow-tooltip />
      <el-table-column label="支付方式" prop="payTypeLabel" show-overflow-tooltip>
        <template #default="{ row }: { row: EaTask }">
          <span v-if="row.payTypeLabel"> {{ (row.payTypeLabel as LabelValue).label }} </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" :width="180">
        <template #default="{ row }: { row: EaTask }">
          <el-space>
            <el-button
              v-has-permission="'detail'"
              type="primary"
              text
              bg
              size="small"
              @click="handleOperation('detail', row.id)"
            >
              详情
            </el-button>
            <el-button type="primary" text bg size="small" @click="handleOperation('orderReceivingInfo', row.id)">
              接单信息
            </el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="pagination.total"
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 15, 20, 30, 50, 100]"
      small
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="getList()"
      @current-change="getList()"
    />

    <el-dialog v-model="formVisible" width="60%" :title="formTitle" draggable @close="closeForm">
      <Form
        ref="formRef"
        @submitting="(val: boolean) => (submitting = val)"
        @complete="(id?: string, isNew?: boolean) => refreshData(isNew)"
      />

      <template #footer>
        <el-button @click="closeForm">取消</el-button>
        <el-button v-show="addSustainably" type="primary" :loading="submitting" @click="submit(true)">
          保存并继续
        </el-button>
        <el-button type="primary" :loading="submitting" @click="submit()">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="detailVisible" width="60%" title="详情" draggable @close="closeDetail">
      <Detail ref="detailRef" />

      <template #footer>
        <el-button
          v-has-permission="'update'"
          plain
          :icon="Edit"
          type="primary"
          style="position: absolute; left: var(--el-dialog-padding-primary)"
          @click="closeDetailAndOpenForm"
        >
          编辑
        </el-button>
        <el-button @click="closeDetail">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
